<?php


namespace App\Service\Admin;


use App\Dao\CooperativeDao;
use App\Dao\PaymentLogDao;
use App\Dao\PercentageDao;
use App\Dao\UserDao;
use App\Dao\UserEmployerDao;
use App\Dao\UserWithDrawLogDao;
use App\Utils\Excel;
use Hyperf\Di\Annotation\Inject;

class FinanceService
{

    /**
     * 提现记录表
     * @Inject()
     * @var UserWithDrawLogDao
     */
    protected $userWithdrawLogDao;


    /**
     * 抽成记录表
     * @Inject()
     * @var PercentageDao
     */
    protected $percentageDao;

    /**
     * 充值流水
     * @Inject()
     * @var PaymentLogDao
     */
    protected $paymentLogDao;

    /**
     * 用户信息
     * @Inject()
     * @var UserDao
     */
    private $userDao;

    /**
     * 合作商
     * @Inject()
     * @var CooperativeDao
     */
    protected $cooperativeDao;

    /**
     * 悬赏主
     * @Inject()
     * @var UserEmployerDao
     */
    protected $userEmployerDao;


    /**
     * 提现流水
     * @param array $query
     * @return array
     */
    public function getWithdrawList($query = [])
    {
        if (!empty($query)){
           $filter = $this->getQuery($query);
           $where = $filter['where'] ?? [];
        }else{
            $where = [];
        }

        $result = $this->userWithdrawLogDao->getWithDrawLogQuery($where,['page'=>$query['page']??1,'per_page'=>$query['perPage']??20])->toArray();

        return $this->returnData($result);
    }


    /**
     * 平台提成流水
     * @param array $query
     * @return array
     */
    public function getPercentageList($query = [])
    {
        if (!empty($query)){
            $filter = $this->getQuery($query);
            $where = $filter['where'] ?? [];
        }else{
            $where = [];
        }
        $result = $this->percentageDao->getPercentageQuery($where,['page'=>$query['page']??1,'per_page'=>$query['perPage']??20])->toArray();

        return $this->returnData($result);
    }


    /**
     * 悬案主充值流水
     * @param array $query
     * @return array
     */
    public function getRechargeList($query = [])
    {
        if (!empty($query)){
            $filter = $this->getQuery($query);
            $where = $filter['where'] ?? [];
        }else{
            $where = [];
        }

        $result = $this->paymentLogDao->getRechargeQuery($where,['page'=>$query['page']??1,'per_page'=>$query['perPage']??20])->toArray();

        return $this->returnData($result);
    }



    /**
     * 返回数据
     * @param $data
     * @return array
     */
    public function returnData($data)
    {
        $arr = [];
        foreach ($data['data'] as $key=>$item)
        {
            //用户信息
            if (isset($filter['user']) && is_object($filter['user'])){
                $userInfo = $filter['user'];
            }else{
                $userInfo = $this->getUserData($item['user_id']);
            }
            $arr[$key]['avatar'] = $userInfo->avatar ?? '';
            $arr[$key]['nickname'] = $userInfo->nickname ?? '';
            $arr[$key]['phone'] = $userInfo->phone ?? '';
            $arr[$key]['time'] = $item['created_at'];
            $arr[$key]['cooperative'] = $this->getCoopersData($item['cooperative_id']);
            $arr[$key]['money'] = isset($item['gold']) ? $item['gold'] : (isset($item['price']) ? $item['price'] : $item['money']);
            if (isset($item['out_trade_no']) || isset($item['trade_no'])){
                $arr[$key]['trade_no'] = $item['trade_no'];
                $arr[$key]['out_trade_no'] = $item['out_trade_no'];
            }

        }
        //分页数据
        $list['data'] = $arr;
        $list['total'] = $data['total'];
        $list['per_page'] = $data['per_page'];
        $list['current_page'] = $data['current_page'];
        $list['last_page'] = $data['last_page'];

        return $list;
    }



    /**
     * 处理检索条件
     * @param $query
     * @param string $type
     * @return array
     */
    public function getQuery($query,string $type='')
    {
        $where = [];
        foreach ($query as $key=>$item) {
            switch ($key){
                case 'cooper_id':
                    $where['where']['cooperative_id'] = $item;
                    break;
                case 'filter_keyword':  //用户
                    $user = $this->userDao->filterKeyword($item);
                    if ($type == 'percentage'){
                        //查询用户关联的悬赏主
                        $employer = $this->userEmployerDao->first(['user_id'=>$user->id],['id']);
                        $where['where']['employer_id'] = $employer->id ?? '';
                    }else{
                        $where['where']['user_id'] = $user->id;
                    }
                    $where['user'] = $user;
                    break;
                case 'start_date':
                    $where['where']['start_date'] = $item;
                    break;
                case 'end_date':
                    $where['where']['end_date'] = $item;
                    break;
            }
        }

        return $where;
    }


    /**
     * 获取用户信息
     * @param $uid
     * @return \Hyperf\Database\Model\Builder|\Hyperf\Database\Model\Model|object|null
     */
    public function getUserData($uid)
    {
        return $this->userDao->first(['id'=>$uid],['avatar','nickname','phone']);
    }

    /**
     * 获取合作商名称
     * @param $cooper_id
     * @return \Hyperf\Utils\HigherOrderTapProxy|mixed|string|void
     */
    public function getCoopersData($cooper_id)
    {
        $ret = $this->cooperativeDao->first(['id'=>$cooper_id],['nickname']);
        return $ret->nickname ?? '';
    }

    /**
     * 导出流水
     * @param $param
     * @param $query
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     */
    public function LogExport($param,$query)
    {
        $head = ['用户','手机号/账号','时间','金额','合作商'];//表头
        $body = [];//导出的数据
        switch ($param['type']){
            case 'withdraw':
                $list = $this->getWithdrawList($query);
                $title = '用户提现流水';
                break;
            case 'percentage':
                $list = $this->getPercentageList($query);
                $title = '平台提成流水';
                break;
            default:
                $list = $this->getRechargeList($query);
                $title = '悬赏主充值流水';
                break;
        }

        foreach ($list['data'] as $item){
            if (is_array($item)){
                array_push($body,[
                    $item['nickname'],
                    $item['phone'],
                    $item['time'],
                    $item['money'],
                    $item['cooperative']
                ]);
            }
        }
        return Excel::export(
            $title,
            $body,
            $head
        );
    }

}